/* MAKEFNT.C
 * Font data creation utility
 *************
 * 29.08.2000 : Toni R„s„nen
 *              modifications/documentation for open source
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include "gfx2.h"
#include "mpack.h"
#include <sys/movedata.h>

extern void VBE2flip (void);

FILE *tied;
int i,x,y,z,size,w;
char *pack;

unsigned short makew ( char r, char g, char b)
{  r >>= 1; g >>= 1; b >>= 1;
   if (r > 31) r = 31;
   if (g > 31) g = 31;
   if (b > 31) b = 31;
   return ( (r << 10) + (g << 5) + (b) );
}


// convert an 8bit paletted area to 16-bit
void convto16bit (char *fr, short *to, char *pal, int size)
{  int i;
   unsigned short w;
   unsigned char c;
   for (i = 0; i < size; i++)
     {  c = *(fr+i);
        w = makew( *(pal+c*3+0), *(pal+c*3+1), *(pal+c*3+2) );
        *(to+i) = w;
     }

}


//-------------------------------------------------------------
// from *ruutu(8bit) to *kuva(RGB_565)
void getpicRGB565 (int x1, int y1, int x2, int y2, unsigned short *kuva)
{
  int xsize,ysize,n,yco,xco,xadd,offs,r,g,b,c;
  unsigned short w;
  xsize = (x2-x1+1);
  ysize = (y2-y1+1);

  *((int*)(kuva+0)) = xsize;
  *((int*)(kuva+2)) = ysize;

  xadd = sxsize-xsize;
  offs = y1*sxsize+x1;
  n = 4;

  for (yco=0; yco<ysize; yco++)
    { for (xco=0; xco<xsize; xco++)
        {  c = *((unsigned char*)(ruutu)+offs++);
           r = gen_palette[c*3+0] >> 1; // 5bits
           g = gen_palette[c*3+1] >> 0; // 6bits
           b = gen_palette[c*3+2] >> 1; // 5bits
           w = (r << 11) + (g << 5) + b;
           *((kuva)+n++) = w;

           putp (xco+x1,yco+y1+100,c);
        }
      offs = offs + xadd;
    }
}


void savefont (char *src, char *trg, int ysize, int count)
{  short c;
   UnpackLBM (src,ruutu);
   setpale (64,64,64);

   spritedest = ruutu;
//   convto16bit (ruutu2, (short*) ruutu, (char*) &gen_palette, 640*480);

   flip();

   tied = fopen (trg,"wb");

   fwrite ( &ysize, 4,1, tied);

   x = 0; y = 0;
   for (i = 32; i < count; i++)
     {
        w = 1;
        while ( (c=gpix (x+w-1,y+ysize)) == 1) w++;

        drawcolor = 0xffff;
        getpic (x,y,x+w-1,y+ysize-1, ruutu2);
        aline  (x,y,x+w-1,y+ysize-1);

        size = spackmem (ruutu2, pack, w*ysize+8);
        fwrite (&w, 4,1, tied);
        fwrite (&size, 4,1, tied);
        fwrite (pack, size,1, tied);

        x += w;
        if (x > 304)
          {  x = 0; y += ysize+1;  }
     }
   size = 0; fwrite (&size, 4,1, tied);

   flip();

   fclose (tied);
}

int main (void)
{
   ruutu = (char*) malloc (640*480*2);
   ruutu2 = (char*) malloc (640*480*2);
   pack = (char*) malloc (16384);

   set320();

   savefont ("gfx/font2.lbm", "tiny.f", 8, 123);
   savefont ("gfx/font3.lbm", "med.f", 10, 155);

//   getch();

   textmode (03);
}
